import Vue from 'vue'
import VueRouter from 'vue-router'

/**
 * 重写路由的push replace方法
 * 解决，相同路由跳转时，报错
 */
const originalPush = VueRouter.prototype.push
const originalReplace = VueRouter.prototype.replace

VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) {
    return originalPush.call(this, location, onResolve, onReject)
  }
  return originalPush.call(this, location).catch((err) => err)
}
VueRouter.prototype.replace = function replace (location, onResolve, onReject) {
  if (onResolve || onReject) {
    return originalReplace.call(this, location, onResolve, onReject)
  }
  return originalReplace.call(this, location).catch((err) => err)
}

Vue.use(VueRouter)

export const routes = [
  {
    path: '/',
    redirect: '/home', //重定向
  },
  {
    path: '/home',
    name: 'Home',
    meta: { title: '首页' },
    component: () => import('@/views/home.vue'),//h5审批流页面
  },
  {
    path: '/approvalDetail',
    name: 'approvalDetail',
    meta: { title: '审批详情' },
    component: () => import('@/views/approvalDetail.vue'),
  },
  {
    path: '/test',
    name: 'test',
    meta: { title: '测试' },
    component: () => import('@/views/test.vue'),
  },
  {
    path: '/userInfo',
    name: 'userInfo',//sass用到
    meta: { title: '用户信息' },
    component: () => import('@/views/userInfo.vue'),
  },
  {
    path: '/ui/:mid',
    name: 'ui',//访客预约
    meta: { title: '访客预约' },
    component: () => import('@/views/ui.vue'),
  },
  {
    path: '/ud/:mid',
    name: 'ud',
    meta: { title: '访客详情' },
    component: () => import('@/views/ud.vue'),
  },
  {
    path: '/uc/:mid',
    name: 'uc',
    meta: { title: '用户访客详情' },
    component: () => import('@/views/uc.vue'),
  },
  {
    path: '/preview/:url',
    name: 'preview',
    meta: { title: '文件预览' },
    component: () => import('@/views/preview.vue'),
  },
  {
    path: '/edit',
    name: 'edit',
    meta: { title: '审批操作' },
    component: () => import('@/views/edit.vue'),
  },
]

const router = new VueRouter({
  routes,
  scrollBehavior (to, from, savedPosition) {
    // console.log('scrollBehavior',to,from,'savedPosition',savedPosition)
    if (savedPosition) {
      return savedPosition
    }
    return { x: 0, y: 0 }
    // 异步滚动操作
    // return new Promise((resolve) => {
    //   setTimeout(() => {
    //   resolve({ x: 0, y: 1 });
    //   }, 0);
    // });
  },
})

router.beforeEach((to, from, next) => {
  const { meta } = to
  if (meta && meta.title) {
    document.title = meta.title
  }
  next()
})

router.onError((error) => {
  console.error(error)
  console.log('路由报错啦')
})

export default router
